package com.etone.autotesting.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.etone.autotesting.listener.WebServiceClassAnnotationListener;
import com.impetus.annovention.Discoverer;
import com.impetus.annovention.Filter;
import com.impetus.annovention.FilterImpl;

/**
 * 
 * @author chenzhichao
 * 
 */
public class ClassUtil {
	/**
 * 
 */
	private static Map<String, Class> iServiceCalss;

	/**
	 * 初始化全部接口服务类
	 */
	private static void initAllIServiceClass() {
		Discoverer discoverer = new Discoverer() {

			@Override
			public Filter getFilter() {
				return new FilterImpl();
			}

			@Override
			public URL[] findResources() {
				List<URL> urlList = new ArrayList<URL>();
				// getLibFile();//
				File rootFile =new File(this.getClass().getResource("/").getFile().replaceFirst("/", ""));
				if (!rootFile.getPath().endsWith("lib")) {
					String lobFile = rootFile.getParent() + "\\" + "lib";
					rootFile = new File(lobFile);
					System.out.println(rootFile);
				}
				ClassFileFilter filter = new ClassFileFilter();
				File[] fileList = rootFile.listFiles(filter);				
				String path = "file:" + fileList[0].getAbsolutePath();
				try {
					System.out.println(path);
					urlList.add(new URL(path));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
				return urlList.toArray(new URL[urlList.size()]);
			}
		};
		// Register class annotation listener
		WebServiceClassAnnotationListener classlistener = new WebServiceClassAnnotationListener();
		discoverer.addAnnotationListener(classlistener);
		// Fire it
		discoverer.discover();
		//Return Value
		iServiceCalss = classlistener.getClassMap();
	}

	private static File getLibFile()
	{
		String logPath = ClassLoader.getSystemResource("META-INF/log4jUdp.properties").getPath();
		System.out.println(logPath);
		File logFile = new File(logPath);
		File parentPath = logFile.getParentFile().getParentFile().getParentFile();
		String libPath = parentPath.getPath().replace("file:\\", "");
		System.out.println(libPath);		
		File path = new File(libPath);
		System.out.println(path.getPath());
		return path;
	}
	
	/**
	 * 获取对应类名的Class
	 * 
	 * @param className
	 * @return
	 */
	public static Class getSearchClass(String className) {
		if (iServiceCalss == null || iServiceCalss.size() <= 0)
			initAllIServiceClass();
		String interfaceName = "i" + className.toLowerCase();
		if (iServiceCalss.containsKey(interfaceName))
			return iServiceCalss.get(interfaceName);
		else
			return null;
	}

}


